from src.choice_api.utils import data_str2timestamp, sort_by_first_element


def parse_internal_online_data(data, columns_lst):
    if data is None or "list" not in data:
        return None

    data_lst = data["list"]
    if not data_lst:
        data_lst = []

    # 真实要获取的字段
    total_columns = ["toc", "tp", "tn", "cod", "pH"]
    if isinstance(columns_lst, str) and columns_lst in total_columns:
        columns_lst = [columns_lst]

    elif isinstance(columns_lst, list) or len(columns_lst) > 0:
        target_correct_columns = []
        for target_column in columns_lst:
            if target_column in total_columns:
                target_correct_columns.append(target_column)
        if len(target_correct_columns) > 0:
            columns_lst = target_correct_columns
        else:
            columns_lst = total_columns
    else:
        columns_lst = total_columns

    param_mapping = {
        "toc": "TOC",
        "tp": "TP",
        "tn": "TN",
        "cod": "COD",
        "pH": "pH",
    }


    # 单表csv解析
    # res_columns = ["time"]
    # res_data = [[x["time"]] for x in company_lst[list(company_lst.keys())[0]]]
    #
    # for k, val_lst in company_lst.items():
    #     for param in columns_lst:
    #         res_columns.append(f"{k} {param_mapping[param]}")
    #         for idx, val in enumerate(val_lst):
    #             res_data[idx].append(val[param])
    # return {
    #     "res_columns": res_columns,
    #     "res_data": res_data,
    # }

    # 单表时序指标形式
    res_columns = []
    res_data = {}

    for param in columns_lst:
        label = f"港区厂内在线数据 {param_mapping[param]} "
        res_columns.append(label)
        res_item_data = []
        for idx, val in enumerate(data_lst):
            if param not in val or val[param] == "":
                continue
            res_item_data.append([data_str2timestamp(val["time"]), val[param]])
        res_data[label] = sort_by_first_element(res_item_data)

    return {
        "res_columns": res_columns,
        "res_data": res_data
    }
